﻿using CPFrameWork.Global;
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft;
using BusinessManage.Common;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using CPFrameWork.Utility.DbOper;
using CPFrameWork.Utility;
using Microsoft.AspNetCore.Mvc;

namespace BusinessManage.OrderInfo
{
	public class OrderDataSyncController : CPWebApiBaseController
	{

		[HttpGet]
		public string GetInfo()
		{
			return "OK";
		}
		[HttpGet]
		//
		public string SyncOrderData(string start = "2018-10-01", string end = "2018-10-03", string orderid = "1807071012083094,1807202245241049,1807202253491049", int type = 1)
		{

			return SynOrderData(Convert.ToDateTime(start+" 00:00:00"), Convert.ToDateTime(end+" 23:59:59"), orderid, type);
		}
		DbHelper _helper = new DbHelper("CPYKWL", CPAppContext.CurDbType());
		/// <summary>
		/// 同步订单数据 并更新至物流系统相应的表
		/// </summary>
		/// <param name="start">发货时间查询 开始时间</param>
		/// <param name="end">发货时间查询 结束时间</param>
		/// <param name="orderids">订单编号 交易id，用英文,分隔例如:1801231520368768,1801231521238768</param>
		/// <param name="type">同步类型  1为按订单编号 同步   2为按发货时间区间进行同步</param>
		public string SynOrderData(DateTime start, DateTime end, string orderids = "1", int type = 1,int pageno=1,int pagesize=50)
		{
			//1、获取url、token值、时间间隔
			string OrderUrl = CPUtils.Configuration.GetSection("AppSettings")["Url"];
			string tokenId = CPUtils.Configuration.GetSection("AppSettings")["TokenId"];
			string period = CPUtils.Configuration.GetSection("AppSettings")["Period"];
            int currentPage = 1;
            int totalPage = 1;
            //do while循环调取,当当前页大于总页数时，不再执行  
            do
            {
                currentPage++;
                //获取时间戳
                string currentTimeStamp = TimeStamp.GetTheTimeStamp(true, DateTime.UtcNow);
                string historyTimeStamp = TimeStamp.GetTheTimeStamp(true, DateTime.UtcNow.AddDays(Convert.ToInt32(period)));

                //2、参数
                SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
                if (type == 1)
                {
                    sParaTemp.Add("tid", orderids);
                }
                else if (type == 2)
                {
                    sParaTemp.Add("wait_delivery_time_start", start.ToString("yyyy-MM-dd HH:mm:ss"));
                    sParaTemp.Add("wait_delivery_time_end", end.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                sParaTemp.Add("shop_id", "3");

                sParaTemp.Add("timestamp", currentTimeStamp);
                sParaTemp.Add("method", "trade.get.apilistall");
                sParaTemp.Add("format", "json");
                sParaTemp.Add("sign_type", "MD5");
                sParaTemp.Add("v", "v1");
                sParaTemp.Add("page_no", pageno.ToString());
                sParaTemp.Add("page_size", pagesize.ToString());
                //3、调取生产签名的算法  得到sign值
                string signString = "";
                signString = CreateSign.CreateSignString(sParaTemp, tokenId);

                SortedDictionary<string, string> allPara = new SortedDictionary<string, string>();
                allPara = sParaTemp;
                allPara.Add("sign", signString);
                //得到序列化的参数值,拼接成"key1=value1&key2=value2"形式
                string data = BusinessManage.Common.wphttppost.datapost(allPara);

                //4、获取接口中返回的数据
                string result = "";
                try
                {
                    result = BusinessManage.Common.wphttppost.Post(data, OrderUrl, 6);
                    //-------从接口获取数据成功，写入日志
                }
                catch (Exception ex)
                {
                    //-------从接口获取数据失败，写入日志
                    return "从接口获取数据失败 ：" + ex.Message;
                }

                //5、解析数据，插入原始表，添加同步时间
                JObject joOrdersResult = (JObject)JsonConvert.DeserializeObject(result);
                if (joOrdersResult["error"].ToString().Equals(""))
                {
                    if (string.IsNullOrEmpty(joOrdersResult["result"].ToString()))
                    {
                        return "未获取需要同步的订单数据";
                    }
                    JToken ordersResult = joOrdersResult["result"];
                    if (ordersResult != null && ((Newtonsoft.Json.Linq.JContainer)ordersResult).Count > 0)
                    {
                        pageno++;
                        JToken ordersList = ordersResult["list"];
                        JToken pageCount = ordersResult["page_total"];
                        totalPage = Convert.ToInt32(pageCount.ToString());     //总页数

                        StringBuilder orderBaseString = new StringBuilder();   //原始表同步语句
                        StringBuilder updateOrderString = new StringBuilder(); //物流系统订单相关表更新语句
                        DateTime sychTime = DateTime.Now;
                        #region 【拼接同步订单、商品信息sql】
                        foreach (JProperty jpOrderInfo in ordersList)
                        {

                            //获取某一订单基本信息   获取属性名称jp.Name、值jp.Value
                            JToken orderBaseInfo = jpOrderInfo.Value;                                  //订单信息
                            JToken sellerInfo = orderBaseInfo["seller_id---extend_table"];             //业务员信息
                            JToken agentInfo = orderBaseInfo["agent_id---extend_table"];               //超市代理信息
                            JToken companyInfo = orderBaseInfo["business_company_id---extend_table"];  //公司信息
                            JToken deptInfo = orderBaseInfo["business_dept_id---extend_table"];        //销售部信息
                            JToken groupInfo = orderBaseInfo["business_group_id---extend_table"];      //销售组信息
                            JToken marketInfo = orderBaseInfo["supermarket_id---extend_table"];        //超市信息
                            string tid = orderBaseInfo["tid"].ToString();
                            int? shop_id = (int?)orderBaseInfo["shop_id"];
                            int? user_id = (int?)orderBaseInfo["user_id"];
                            int? dlytmpl_id = (int?)orderBaseInfo["dlytmpl_id"];
                            string dlytmpl_ids = orderBaseInfo["dlytmpl_ids"].ToString();
                            string ziti_addr = orderBaseInfo["ziti_addr"].ToString();
                            string status = orderBaseInfo["status"].ToString();
                            string cancel_status = orderBaseInfo["cancel_status"].ToString();
                            string cancel_reason = orderBaseInfo["cancel_reason"].ToString();
                            string pay_type = orderBaseInfo["pay_type"].ToString();
                            decimal? payment = (decimal?)orderBaseInfo["payment"] == null ? 0 : (decimal?)orderBaseInfo["payment"];
                            decimal? points_fee = (decimal?)orderBaseInfo["points_fee"] == null ? 0 : (decimal?)orderBaseInfo["points_fee"];
                            decimal? total_fee = (decimal?)orderBaseInfo["total_fee"] == null ? 0 : (decimal?)orderBaseInfo["total_fee"];
                            decimal? post_fee = (decimal?)orderBaseInfo["post_fee"] == null ? 0 : (decimal?)orderBaseInfo["post_fee"];
                            decimal? payed_fee = (decimal?)orderBaseInfo["payed_fee"] == null ? 0 : (decimal?)orderBaseInfo["payed_fee"];
                            bool? seller_rate = (bool?)orderBaseInfo["seller_rate"];
                            string receiver_name = orderBaseInfo["receiver_name"].ToString();
                            int? created_time = (int?)orderBaseInfo["created_time"];
                            int? pay_time = (int?)orderBaseInfo["pay_time"];
                            int? consign_time = (int?)orderBaseInfo["consign_time"];
                            int? end_time = (int?)orderBaseInfo["end_time"];
                            int? modified_time = (int?)orderBaseInfo["modified_time"];
                            int? timeout_action_time = (int?)orderBaseInfo["timeout_action_time"];
                            int? send_time = (int?)orderBaseInfo["send_time"];
                            string receiver_state = orderBaseInfo["receiver_state"].ToString();
                            string receiver_city = orderBaseInfo["receiver_city"].ToString();
                            string receiver_district = orderBaseInfo["receiver_district"].ToString();
                            string receiver_address = orderBaseInfo["receiver_address"].ToString();
                            string receiver_zip = orderBaseInfo["receiver_zip"].ToString();
                            string receiver_mobile = orderBaseInfo["receiver_mobile"].ToString();
                            string receiver_phone = orderBaseInfo["receiver_phone"].ToString();
                            string title = orderBaseInfo["title"].ToString();
                            decimal? discount_fee = (decimal?)orderBaseInfo["discount_fee"] == null ? 0 : (decimal?)orderBaseInfo["discount_fee"];
                            int? consume_point_fee = (int?)orderBaseInfo["consume_point_fee"];
                            string buyer_message = orderBaseInfo["buyer_message"].ToString();
                            bool? need_invoice = (bool?)orderBaseInfo["need_invoice"];
                            string invoice_name = orderBaseInfo["invoice_name"].ToString();
                            string invoice_type = orderBaseInfo["invoice_type"].ToString();
                            string invoice_main = orderBaseInfo["invoice_main"].ToString();
                            string invoice_vat_main = orderBaseInfo["invoice_vat_main"].ToString();
                            decimal? adjust_fee = (decimal?)orderBaseInfo["adjust_fee"] == null ? 0 : (decimal?)orderBaseInfo["adjust_fee"];
                            string trade_from = orderBaseInfo["trade_from"].ToString();
                            int? itemnum = (int?)orderBaseInfo["itemnum"];
                            string shop_flag = orderBaseInfo["shop_flag"].ToString();
                            string shop_memo = orderBaseInfo["shop_memo"].ToString();
                            string buyer_area = orderBaseInfo["buyer_area"].ToString();
                            int? area_id = (int?)orderBaseInfo["area_id"];
                            string step_trade_status = orderBaseInfo["step_trade_status"].ToString();
                            decimal? total_weight = (decimal?)orderBaseInfo["total_weight"] == null ? 0 : (decimal?)orderBaseInfo["total_weight"];
                            decimal? step_paid_fee = (decimal?)orderBaseInfo["step_paid_fee"] == null ? 0 : (decimal?)orderBaseInfo["step_paid_fee"];
                            string shipping_type = orderBaseInfo["shipping_type"].ToString();
                            int obtain_point_fee = (int)orderBaseInfo["obtain_point_fee"];
                            string trade_memo = orderBaseInfo["trade_memo"].ToString();
                            bool? buyer_rate = (bool?)orderBaseInfo["buyer_rate"];
                            bool? is_part_consign = (bool?)orderBaseInfo["is_part_consign"];
                            int? real_point_fee = (int?)orderBaseInfo["real_point_fee"];
                            string ip = orderBaseInfo["ip"].ToString();
                            bool? anony = (bool?)orderBaseInfo["anony"];
                            string is_clearing = orderBaseInfo["is_clearing"].ToString();
                            string disabled = orderBaseInfo["disabled"].ToString();
                            string ziti_memo = orderBaseInfo["ziti_memo"].ToString();
                            string code = orderBaseInfo["code"].ToString();
                            int? seller_id = (int?)orderBaseInfo["seller_id"];
                            int? agent_id = (int?)orderBaseInfo["agent_id"];
                            int? wait_delivery_time = (int?)orderBaseInfo["wait_delivery_time"];
                            int? accounting_id = (int?)orderBaseInfo["accounting_id"];
                            bool? is_lock = (bool?)orderBaseInfo["is_lock"];
                            bool? is_auth = (bool?)orderBaseInfo["is_auth"];
                            decimal? deposit_amount = (decimal?)orderBaseInfo["deposit_amount"] == null ? 0 : (decimal?)orderBaseInfo["deposit_amount"];
                            decimal? commission_amount = (decimal?)orderBaseInfo["commission_amount"] == null ? 0 : (decimal?)orderBaseInfo["commission_amount"];
                            int? loss_number = (int?)orderBaseInfo["loss_number"];
                            decimal? valueadded_amount = (decimal?)orderBaseInfo["valueadded_amount"] == null ? 0 : (decimal?)orderBaseInfo["valueadded_amount"];
                            string valueadded_content = orderBaseInfo["valueadded_content"].ToString();
                            string seller_dept_code = orderBaseInfo["seller_dept_code"].ToString();
                            string seller_group_code = orderBaseInfo["seller_group_code"].ToString();
                            string supermarket_code = orderBaseInfo["supermarket_code"].ToString();
                            int? order_owner = (int?)orderBaseInfo["order_owner"];
                            string order_source = orderBaseInfo["order_source"].ToString();
                            string order_type = orderBaseInfo["order_type"].ToString();
                            int? become_wait_time = (int?)orderBaseInfo["become_wait_time"];
                            int? adjust_number = (int?)orderBaseInfo["adjust_number"];
                            string invoice_detail = orderBaseInfo["invoice_detail"].ToString();
                            bool? show_part_pay = (bool?)orderBaseInfo["show_part_pay"];
                            string pre_tid = orderBaseInfo["pre_tid"].ToString();
                            decimal? total_refund_fee = (decimal?)orderBaseInfo["total_refund_fee"] == null ? 0 : (decimal?)orderBaseInfo["total_refund_fee"];
                            string pay_step = orderBaseInfo["pay_step"].ToString();
                            decimal? commission_adjust_amount = (decimal?)orderBaseInfo["commission_adjust_amount"] == null ? 0 : (decimal?)orderBaseInfo["commission_adjust_amount"];
                            decimal? total_refund_fee_user = (decimal?)orderBaseInfo["total_refund_fee_user"] == null ? 0 : (decimal?)orderBaseInfo["total_refund_fee_user"];
                            int? pre_created_time = (int?)orderBaseInfo["pre_created_time"];
                            string seller_dept_id = orderBaseInfo["seller_dept_id"].ToString();
                            string seller_group_id = orderBaseInfo["seller_group_id"].ToString();
                            string supermarket_id = orderBaseInfo["supermarket_id"].ToString();
                            string company_id = orderBaseInfo["company_id"].ToString();
                            int? business_dept_id = (int?)orderBaseInfo["business_dept_id"];
                            int? business_group_id = (int?)orderBaseInfo["business_group_id"];
                            int? business_company_id = (int?)orderBaseInfo["business_company_id"];
                            int? area_account = (int?)orderBaseInfo["area_account"];
                            int? area_manager = (int?)orderBaseInfo["area_manager"];
                            int? remittance = (int?)orderBaseInfo["remittance"];
                            string factory = orderBaseInfo["factory"].ToString();
                            string storeroom = orderBaseInfo["storeroom"].ToString();
                            int? admin_memo = (int?)orderBaseInfo["admin_memo"];
                            string admin_reason = orderBaseInfo["admin_reason"].ToString();
                            string seller_name = string.IsNullOrEmpty(sellerInfo.ToString()) ? "" : sellerInfo["name"].ToString();
                            string seller_mobile = string.IsNullOrEmpty(sellerInfo.ToString()) ? "" : sellerInfo["mobile"].ToString();
                            string agent_name = string.IsNullOrEmpty(agentInfo.ToString()) ? "" : agentInfo["name"].ToString();
                            string agent_mobile = string.IsNullOrEmpty(agentInfo.ToString()) ? "" : agentInfo["mobile"].ToString();
                            string supermarket_name = string.IsNullOrEmpty(marketInfo.ToString()) ? "" : marketInfo["name"].ToString();
                            string business_group_name = string.IsNullOrEmpty(groupInfo.ToString()) ? "" : groupInfo["name"].ToString();
                            string business_dept_name = string.IsNullOrEmpty(deptInfo.ToString()) ? "" : deptInfo["name"].ToString();
                            string business_company_name = string.IsNullOrEmpty(companyInfo.ToString()) ? "" : companyInfo["name"].ToString();
                            #region 【原始表，订单基本信息 插入数据sql】
                            //原始表，订单基本信息 插入数据sql
                            orderBaseString.Append("insert into O_systrade_trade (tid,shop_id,user_id,dlytmpl_id,dlytmpl_ids,ziti_addr,status,step_trade_status,cancel_status,cancel_reason,pay_type,payment,points_fee,total_fee,post_fee,payed_fee,total_refund_fee,total_refund_fee_user,seller_rate,receiver_name,created_time,pre_created_time,pay_time,consign_time,end_time,modified_time,timeout_action_time,send_time,become_wait_time,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,title,discount_fee,consume_point_fee,buyer_message,need_invoice,invoice_name,invoice_type,invoice_main,invoice_detail,invoice_vat_main,adjust_fee,trade_from,itemnum,shop_flag,shop_memo,buyer_area,area_id,total_weight,step_paid_fee,shipping_type,obtain_point_fee,trade_memo,buyer_rate,is_part_consign,real_point_fee,ip,anony,is_clearing,disabled,ziti_memo,seller_dept_code,seller_group_code,supermarket_code,code,accounting_id,seller_id,agent_id,wait_delivery_time,is_lock,is_auth,deposit_amount,commission_amount,commission_adjust_amount,loss_number,adjust_number,valueadded_amount,valueadded_content,order_owner,order_source,show_part_pay,order_type,pre_tid,pay_step,seller_dept_id,seller_group_id,supermarket_id,company_id,business_dept_id,business_group_id,business_company_id,area_accoun,area_manager,remittance,factory,storeroom,admin_memo,admin_reason,seller_name,seller_mobile,agent_name,agent_mobile,supermarket_name,business_group_name,business_dept_name,business_company_name,syntime) values(");
                            orderBaseString.Append("'" + tid + "',");
                            orderBaseString.Append("'" + shop_id + "',");
                            orderBaseString.Append("'" + user_id + "',");
                            orderBaseString.Append("'" + dlytmpl_id + "',");
                            orderBaseString.Append("'" + dlytmpl_ids + "',");
                            orderBaseString.Append("'" + ziti_addr + "',");
                            orderBaseString.Append("'" + status + "',");
                            orderBaseString.Append("'" + step_trade_status + "',");
                            orderBaseString.Append("'" + cancel_status + "',");
                            orderBaseString.Append("'" + cancel_reason + "',");
                            orderBaseString.Append("'" + pay_type + "',");
                            orderBaseString.Append("'" + payment + "',");
                            orderBaseString.Append("'" + points_fee + "',");
                            orderBaseString.Append("'" + total_fee + "',");
                            orderBaseString.Append("'" + post_fee + "',");
                            orderBaseString.Append("'" + payed_fee + "',");
                            orderBaseString.Append("'" + total_refund_fee + "',");
                            orderBaseString.Append("'" + total_refund_fee_user + "',");
                            orderBaseString.Append("'" + seller_rate + "',");
                            orderBaseString.Append("'" + receiver_name + "',");
                            orderBaseString.Append("'" + created_time + "',");
                            orderBaseString.Append("'" + pre_created_time + "',");
                            orderBaseString.Append("'" + pay_time + "',");
                            orderBaseString.Append("'" + consign_time + "',");
                            orderBaseString.Append("'" + end_time + "',");
                            orderBaseString.Append("'" + modified_time + "',");
                            orderBaseString.Append("'" + timeout_action_time + "',");
                            orderBaseString.Append("'" + send_time + "',");
                            orderBaseString.Append("'" + become_wait_time + "',");
                            orderBaseString.Append("'" + receiver_state + "',");
                            orderBaseString.Append("'" + receiver_city + "',");
                            orderBaseString.Append("'" + receiver_district + "',");
                            orderBaseString.Append("'" + receiver_address + "',");
                            orderBaseString.Append("'" + receiver_zip + "',");
                            orderBaseString.Append("'" + receiver_mobile + "',");
                            orderBaseString.Append("'" + receiver_phone + "',");
                            orderBaseString.Append("'" + title + "',");
                            orderBaseString.Append("'" + discount_fee + "',");
                            orderBaseString.Append("'" + consume_point_fee + "',");
                            orderBaseString.Append("'" + buyer_message + "',");
                            orderBaseString.Append("'" + need_invoice + "',");
                            orderBaseString.Append("'" + invoice_name + "',");
                            orderBaseString.Append("'" + invoice_type + "',");
                            orderBaseString.Append("'" + invoice_main + "',");
                            orderBaseString.Append("'" + invoice_detail + "',");
                            orderBaseString.Append("'" + invoice_vat_main + "',");
                            orderBaseString.Append("'" + adjust_fee + "',");
                            orderBaseString.Append("'" + trade_from + "',");
                            orderBaseString.Append("'" + itemnum + "',");
                            orderBaseString.Append("'" + shop_flag + "',");
                            orderBaseString.Append("'" + shop_memo + "',");
                            orderBaseString.Append("'" + buyer_area + "',");
                            orderBaseString.Append("'" + area_id + "',");
                            orderBaseString.Append("'" + total_weight + "',");
                            orderBaseString.Append("'" + step_paid_fee + "',");
                            orderBaseString.Append("'" + shipping_type + "',");
                            orderBaseString.Append("'" + obtain_point_fee + "',");
                            orderBaseString.Append("'" + trade_memo + "',");
                            orderBaseString.Append("'" + buyer_rate + "',");
                            orderBaseString.Append("'" + is_part_consign + "',");
                            orderBaseString.Append("'" + real_point_fee + "',");
                            orderBaseString.Append("'" + ip + "',");
                            orderBaseString.Append("'" + anony + "',");
                            orderBaseString.Append("'" + is_clearing + "',");
                            orderBaseString.Append("'" + disabled + "',");
                            orderBaseString.Append("'" + ziti_memo + "',");
                            orderBaseString.Append("'" + seller_dept_code + "',");
                            orderBaseString.Append("'" + seller_group_code + "',");
                            orderBaseString.Append("'" + supermarket_code + "',");
                            orderBaseString.Append("'" + code + "',");
                            orderBaseString.Append("'" + accounting_id + "',");
                            orderBaseString.Append("'" + seller_id + "',");
                            orderBaseString.Append("'" + agent_id + "',");
                            orderBaseString.Append("'" + wait_delivery_time + "',");
                            orderBaseString.Append("'" + is_lock + "',");
                            orderBaseString.Append("'" + is_auth + "',");
                            orderBaseString.Append("'" + deposit_amount + "',");
                            orderBaseString.Append("'" + commission_amount + "',");
                            orderBaseString.Append("'" + commission_adjust_amount + "',");
                            orderBaseString.Append("'" + loss_number + "',");
                            orderBaseString.Append("'" + adjust_number + "',");
                            orderBaseString.Append("'" + valueadded_amount + "',");
                            orderBaseString.Append("'" + valueadded_content + "',");
                            orderBaseString.Append("'" + order_owner + "',");
                            orderBaseString.Append("'" + order_source + "',");
                            orderBaseString.Append("'" + show_part_pay + "',");
                            orderBaseString.Append("'" + order_type + "',");
                            orderBaseString.Append("'" + pre_tid + "',");
                            orderBaseString.Append("'" + pay_step + "',");
                            orderBaseString.Append("'" + seller_dept_id + "',");
                            orderBaseString.Append("'" + seller_group_id + "',");
                            orderBaseString.Append("'" + supermarket_id + "',");
                            orderBaseString.Append("'" + company_id + "',");
                            orderBaseString.Append("'" + business_dept_id + "',");
                            orderBaseString.Append("'" + business_group_id + "',");
                            orderBaseString.Append("'" + business_company_id + "',");
                            orderBaseString.Append("'" + area_account + "',");
                            orderBaseString.Append("'" + area_manager + "',");
                            orderBaseString.Append("'" + remittance + "',");
                            orderBaseString.Append("'" + factory + "',");
                            orderBaseString.Append("'" + storeroom + "',");
                            orderBaseString.Append("'" + admin_memo + "',");
                            orderBaseString.Append("'" + admin_reason + "',");
                            orderBaseString.Append("'" + seller_name + "',");
                            orderBaseString.Append("'" + seller_mobile + "',");
                            orderBaseString.Append("'" + agent_name + "',");
                            orderBaseString.Append("'" + agent_mobile + "',");
                            orderBaseString.Append("'" + supermarket_name + "',");
                            orderBaseString.Append("'" + business_group_name + "',");
                            orderBaseString.Append("'" + business_dept_name + "',");
                            orderBaseString.Append("'" + business_company_name + "',");
                            orderBaseString.Append("'" + sychTime + "'");
                            orderBaseString.Append(");");

                            #endregion 【原始表，订单基本信息 插入数据sql】


                            #region 【物流系统中相应订单基本信息表，更新数据sql】

                            //物流系统订单基本信息 更新sql
                            updateOrderString.Append("IF EXISTS (select * from YW_OrderInfo where OrderCode='" + tid + "') update YW_OrderInfo set OrderCode='" + tid + "',Title='" + title + "',OrderStatus='" + status + "',OrgId='" + business_company_id + "',OrgName='" + business_company_name + "',SaleDeptId='" + business_dept_id + "',SaleDeptName='" + business_dept_name + "',SaleGroupId='" + business_group_id + "',SaleGroupName='" + business_group_name + "',MarkId='" + supermarket_id + "',MarketName='" + supermarket_name + "',AgentId='" + agent_id + "',AgentName='" + agent_name + "',AgentTel='" + agent_mobile + "',SalemanId='" + seller_id + "',Salesman='" + seller_name + "',SalesmanTel='" + seller_mobile + "',RegionalAccountantId='" + accounting_id + "',CustomerName='" + receiver_name + "',CustomerState='" + receiver_state + "',CustomerCity='" + receiver_city + "',CustomerDistrict='" + receiver_district + "',CustomerAddress='" + receiver_address + "',CustomerZip='" + receiver_zip + "',CustomerMobile='" + receiver_mobile + "',CustomerPhone='" + receiver_phone + "',OrderRoadLoss='" + loss_number + "',CancelStatus='" + cancel_status + "',CancelReason='" + cancel_reason + "',CreateTime=" + TimeStamp.unixTimeToTime(created_time.ToString()) + ",AdjustNumber=" + adjust_number + ",ZitiAddress='" + ziti_addr + "',ZitiMemo='" + ziti_memo + "',IsPartConsign='" + is_part_consign + "',Disabled='" + disabled + "',IsLock='" + is_lock + "',WaitDeliveryTime=" + TimeStamp.unixTimeToTime(wait_delivery_time.ToString()) + ",DeliveryTime=" + TimeStamp.unixTimeToTime(consign_time.ToString()) + ",BecomeWaitTime=" + TimeStamp.unixTimeToTime(become_wait_time.ToString()) + ",RreTid='" + pre_tid + "',Factory='" + factory + "',Storeroom='" + storeroom + "',TotalCount=" + itemnum + ",TradeMemo='" + trade_memo + "' where OrderCode='" + tid + "'");
                            updateOrderString.Append("  ELSE insert into YW_OrderInfo (OrderCode,Title,OrderStatus,OrgId,OrgName,SaleDeptId,SaleDeptName,SaleGroupId,SaleGroupName,MarkId,MarketName,AgentId,AgentName,AgentTel,SalemanId,Salesman,SalesmanTel,RegionalAccountantId,CustomerName,CustomerState,CustomerCity,CustomerDistrict,CustomerAddress,CustomerZip,CustomerMobile,CustomerPhone,OrderRoadLoss,CancelStatus,CancelReason,CreateTime,AdjustNumber,ZitiAddress,ZitiMemo,IsPartConsign,Disabled,IsLock,WaitDeliveryTime,DeliveryTime,BecomeWaitTime,RreTid,Factory,Storeroom,TotalCount,TradeMemo) values('" + tid + "','" + title + "','" + status + "','" + business_company_id + "','" + business_company_name + "','" + business_dept_id + "','" + business_dept_name + "','" + business_group_id + "','" + business_group_name + "','" + supermarket_id + "','" + supermarket_name + "','" + agent_id + "','" + agent_name + "','" + agent_mobile + "','" + seller_id + "','" + seller_name + "','" + seller_mobile + "','" + accounting_id + "','" + receiver_name + "','" + receiver_state + "','" + receiver_city + "','" + receiver_district + "','" + receiver_address + "','" + receiver_zip + "','" + receiver_mobile + "','" + receiver_phone + "','" + loss_number + "','" + cancel_status + "','" + cancel_reason + "'," + TimeStamp.unixTimeToTime(created_time.ToString()) + ",'" + adjust_number + "','" + ziti_addr + "','" + ziti_memo + "','" + is_part_consign + "','" + disabled + "','" + is_lock + "'," + TimeStamp.unixTimeToTime(wait_delivery_time.ToString()) + "," + TimeStamp.unixTimeToTime(consign_time.ToString()) + "," + TimeStamp.unixTimeToTime(become_wait_time.ToString()) + ",'" + pre_tid + "','" + factory + "','" + storeroom + "'," + itemnum + ",'" + trade_memo + "');");

                            #endregion 【物流系统中相应订单基本信息表，更新数据sql】

                            #region 【拼接同步商品信息sql】
                            //获取此订单中商品详细信息
                            JToken orderGoodsList = orderBaseInfo["goods_list"];
                            foreach (JProperty jpGoodsInfo in orderGoodsList)
                            {
                                JToken orderGoodsInfo = jpGoodsInfo.Value;
                                JToken orderCatgoryInfo = orderGoodsInfo["cat_id---extend_table"];  //品种信息   
                                if (orderGoodsInfo["cat_id"].ToString() == "403" || orderGoodsInfo["cat_id"].ToString() == "404")
                                {
                                    string g_oid = orderGoodsInfo["oid"].ToString();
                                    string g_tid = orderGoodsInfo["tid"].ToString();
                                    string g_cat_id = orderGoodsInfo["cat_id"].ToString();
                                    string g_shop_id = orderGoodsInfo["shop_id"].ToString();
                                    string g_user_id = orderGoodsInfo["user_id"].ToString();
                                    string g_item_id = orderGoodsInfo["item_id"].ToString();
                                    string g_sku_id = orderGoodsInfo["sku_id"].ToString();
                                    string g_bn = orderGoodsInfo["bn"].ToString();
                                    string g_title = orderGoodsInfo["title"].ToString();
                                    string g_spec_nature_info = orderGoodsInfo["spec_nature_info"].ToString();
                                    decimal? g_price = (decimal?)orderGoodsInfo["price"] == null ? 0 : (decimal?)orderGoodsInfo["price"];
                                    string g_num = orderGoodsInfo["num"].ToString();
                                    decimal? g_sendnum = (decimal?)orderGoodsInfo["sendnum"] == null ? 0 : (decimal?)orderGoodsInfo["sendnum"];
                                    string g_sku_properties_name = orderGoodsInfo["sku_properties_name"].ToString();
                                    string g_refund_id = orderGoodsInfo["refund_id"].ToString();
                                    bool? g_is_oversold = (bool?)orderGoodsInfo["is_oversold"];
                                    string g_pay_time = orderGoodsInfo["pay_time"].ToString();
                                    string g_end_time = orderGoodsInfo["end_time"].ToString();
                                    string g_consign_time = orderGoodsInfo["consign_time"].ToString();
                                    string g_shipping_type = orderGoodsInfo["shipping_type"].ToString();
                                    string g_bind_oid = orderGoodsInfo["bind_oid"].ToString();
                                    string g_logistics_company = orderGoodsInfo["logistics_company"].ToString();
                                    string g_invoice_no = orderGoodsInfo["invoice_no"].ToString();
                                    decimal? g_divide_order_fee = (decimal?)orderGoodsInfo["divide_order_fee"] == null ? 0 : (decimal?)orderGoodsInfo["divide_order_fee"];
                                    decimal? g_part_mjz_discount = (decimal?)orderGoodsInfo["part_mjz_discount"] == null ? 0 : (decimal?)orderGoodsInfo["part_mjz_discount"];
                                    decimal? g_total_fee = (decimal?)orderGoodsInfo["total_fee"] == null ? 0 : (decimal?)orderGoodsInfo["total_fee"];
                                    decimal? g_payment = (decimal?)orderGoodsInfo["payment"] == null ? 0 : (decimal?)orderGoodsInfo["payment"];
                                    decimal? g_points_fee = (decimal?)orderGoodsInfo["points_fee"] == null ? 0 : (decimal?)orderGoodsInfo["points_fee"];
                                    decimal? g_consume_point_fee = (decimal?)orderGoodsInfo["consume_point_fee"] == null ? 0 : (decimal?)orderGoodsInfo["consume_point_fee"];
                                    decimal? g_total_weight = (decimal?)orderGoodsInfo["total_weight"] == null ? 0 : (decimal?)orderGoodsInfo["total_weight"];
                                    decimal? g_discount_fee = (decimal?)orderGoodsInfo["discount_fee"] == null ? 0 : (decimal?)orderGoodsInfo["discount_fee"];
                                    decimal? g_adjust_fee = (decimal?)orderGoodsInfo["adjust_fee"] == null ? 0 : (decimal?)orderGoodsInfo["adjust_fee"];
                                    string g_modified_time = orderGoodsInfo["modified_time"].ToString();
                                    string g_status = orderGoodsInfo["status"].ToString();
                                    string g_aftersales_status = orderGoodsInfo["aftersales_status"].ToString();
                                    string g_complaints_status = orderGoodsInfo["complaints_status"].ToString();
                                    decimal? g_refund_fee = (decimal?)orderGoodsInfo["refund_fee"] == null ? 0 : (decimal?)orderGoodsInfo["refund_fee"];
                                    decimal? g_refund_fee_user = (decimal?)orderGoodsInfo["refund_fee_user"] == null ? 0 : (decimal?)orderGoodsInfo["refund_fee_user"];
                                    bool? g_buyer_rate = (bool?)orderGoodsInfo["buyer_rate"];
                                    bool? g_anony = (bool?)orderGoodsInfo["anony"];
                                    bool? g_seller_rate = (bool?)orderGoodsInfo["seller_rate"];
                                    decimal? g_cat_service_rate = (decimal?)orderGoodsInfo["cat_service_rate"] == null ? 0 : (decimal?)orderGoodsInfo["cat_service_rate"];
                                    string g_order_from = orderGoodsInfo["order_from"].ToString();
                                    string g_pic_path = orderGoodsInfo["pic_path"].ToString();
                                    string g_timeout_action_time = orderGoodsInfo["timeout_action_time"].ToString();
                                    string g_outer_iid = orderGoodsInfo["outer_iid"].ToString();
                                    string g_outer_sku_id = orderGoodsInfo["outer_sku_id"].ToString();
                                    bool? g_sub_stock = (bool?)orderGoodsInfo["sub_stock"];
                                    string g_dlytmpl_id = orderGoodsInfo["dlytmpl_id"].ToString();
                                    decimal? g_deposit_amount = (decimal?)orderGoodsInfo["deposit_amount"] == null ? 0 : (decimal?)orderGoodsInfo["deposit_amount"];
                                    decimal? g_commission_price = (decimal?)orderGoodsInfo["commission_price"] == null ? 0 : (decimal?)orderGoodsInfo["commission_price"];
                                    decimal? g_commission_amount = (decimal?)orderGoodsInfo["commission_amount"] == null ? 0 : (decimal?)orderGoodsInfo["commission_amount"];
                                    decimal? g_commission_adjust_amount = (decimal?)orderGoodsInfo["commission_adjust_amount"] == null ? 0 : (decimal?)orderGoodsInfo["commission_adjust_amount"];
                                    string g_loss_number = orderGoodsInfo["loss_number"].ToString();
                                    string g_adjust_number = orderGoodsInfo["adjust_number"].ToString();
                                    decimal? g_valueadded_amount = (decimal?)orderGoodsInfo["valueadded_amount"] == null ? 0 : (decimal?)orderGoodsInfo["valueadded_amount"];
                                    string g_valueadded_content = orderGoodsInfo["valueadded_content"].ToString();
                                    string g_wait_delivery_time = orderGoodsInfo["wait_delivery_time"].ToString();
                                    string g_pre_tid = orderGoodsInfo["pre_tid"].ToString();
                                    string g_sub_title = orderGoodsInfo["sub_title"].ToString();
                                    string g_cat_name = orderCatgoryInfo == null ? "" : orderCatgoryInfo["cat_name"].ToString();

                                    //原始表，订单商品详细信息 插入数据sql
                                    orderBaseString.Append("insert into O_systrade_order (oid,tid,cat_id,shop_id,user_id,item_id,sku_id,bn,title,spec_nature_info,price,num,sendnum,sku_properties_name,refund_id,is_oversold,pay_time,end_time,consign_time,shipping_type,bind_oid,logistics_company,invoice_no,divide_order_fee,part_mjz_discount,total_fee,payment,points_fee,consume_point_fee,total_weight,discount_fee,adjust_fee,modified_time,status,aftersales_status,complaints_status,refund_fee,refund_fee_user,buyer_rate,anony,seller_rate,cat_service_rate,order_from,pic_path,timeout_action_time,outer_iid,outer_sku_id,sub_stock,dlytmpl_id,deposit_amount,commission_price,commission_amount,commission_adjust_amount,loss_number,adjust_number,valueadded_amount,valueadded_content,wait_delivery_time,pre_tid,sub_title,cat_name,syntime) values(");
                                    orderBaseString.Append("'" + g_oid + "',");
                                    orderBaseString.Append("'" + g_tid + "',");
                                    orderBaseString.Append("'" + g_cat_id + "',");
                                    orderBaseString.Append("'" + g_shop_id + "',");
                                    orderBaseString.Append("'" + g_user_id + "',");
                                    orderBaseString.Append("'" + g_item_id + "',");
                                    orderBaseString.Append("'" + g_sku_id + "',");
                                    orderBaseString.Append("'" + g_bn + "',");
                                    orderBaseString.Append("'" + g_title + "',");
                                    orderBaseString.Append("'" + g_spec_nature_info + "',");
                                    orderBaseString.Append("'" + g_price + "',");
                                    orderBaseString.Append("'" + g_num + "',");
                                    orderBaseString.Append("'" + g_sendnum + "',");
                                    orderBaseString.Append("'" + g_sku_properties_name + "',");
                                    orderBaseString.Append("'" + g_refund_id + "',");
                                    orderBaseString.Append("'" + g_is_oversold + "',");
                                    orderBaseString.Append("'" + g_pay_time + "',");
                                    orderBaseString.Append("'" + g_end_time + "',");
                                    orderBaseString.Append("'" + g_consign_time + "',");
                                    orderBaseString.Append("'" + g_shipping_type + "',");
                                    orderBaseString.Append("'" + g_bind_oid + "',");
                                    orderBaseString.Append("'" + g_logistics_company + "',");
                                    orderBaseString.Append("'" + g_invoice_no + "',");
                                    orderBaseString.Append("'" + g_divide_order_fee + "',");
                                    orderBaseString.Append("'" + g_part_mjz_discount + "',");
                                    orderBaseString.Append("'" + g_total_fee + "',");
                                    orderBaseString.Append("'" + g_payment + "',");
                                    orderBaseString.Append("'" + g_points_fee + "',");
                                    orderBaseString.Append("'" + g_consume_point_fee + "',");
                                    orderBaseString.Append("'" + g_total_weight + "',");
                                    orderBaseString.Append("'" + g_discount_fee + "',");
                                    orderBaseString.Append("'" + g_adjust_fee + "',");
                                    orderBaseString.Append("'" + g_modified_time + "',");
                                    orderBaseString.Append("'" + g_status + "',");
                                    orderBaseString.Append("'" + g_aftersales_status + "',");
                                    orderBaseString.Append("'" + g_complaints_status + "',");
                                    orderBaseString.Append("'" + g_refund_fee + "',");
                                    orderBaseString.Append("'" + g_refund_fee_user + "',");
                                    orderBaseString.Append("'" + g_buyer_rate + "',");
                                    orderBaseString.Append("'" + g_anony + "',");
                                    orderBaseString.Append("'" + g_seller_rate + "',");
                                    orderBaseString.Append("'" + g_cat_service_rate + "',");
                                    orderBaseString.Append("'" + g_order_from + "',");
                                    orderBaseString.Append("'" + g_pic_path + "',");
                                    orderBaseString.Append("'" + g_timeout_action_time + "',");
                                    orderBaseString.Append("'" + g_outer_iid + "',");
                                    orderBaseString.Append("'" + g_outer_sku_id + "',");
                                    orderBaseString.Append("'" + g_sub_stock + "',");
                                    orderBaseString.Append("'" + g_dlytmpl_id + "',");
                                    orderBaseString.Append("'" + g_deposit_amount + "',");
                                    orderBaseString.Append("'" + g_commission_price + "',");
                                    orderBaseString.Append("'" + g_commission_amount + "',");
                                    orderBaseString.Append("'" + g_commission_adjust_amount + "',");
                                    orderBaseString.Append("'" + g_loss_number + "',");
                                    orderBaseString.Append("'" + g_adjust_number + "',");
                                    orderBaseString.Append("'" + g_valueadded_amount + "',");
                                    orderBaseString.Append("'" + g_valueadded_content + "',");
                                    orderBaseString.Append("'" + g_wait_delivery_time + "',");
                                    orderBaseString.Append("'" + g_pre_tid + "',");
                                    orderBaseString.Append("'" + g_sub_title + "',");
                                    orderBaseString.Append("'" + g_cat_name + "',");
                                    orderBaseString.Append("'" + sychTime + "'");
                                    orderBaseString.Append(");");
                                    string ValueAdded_content = "";
                                    if (!string.IsNullOrEmpty(g_valueadded_content))
                                    {
                                        JArray ja = (JArray)JsonConvert.DeserializeObject(g_valueadded_content);
                                        foreach (JObject o in ja)
                                        {
                                            if (string.IsNullOrEmpty(ValueAdded_content))
                                                ValueAdded_content = o["title"].ToString();
                                            else
                                                ValueAdded_content = ValueAdded_content + "," + o["title"].ToString();
                                        }
                                    }
                                    #region 【拼接更新商品信息sql】
                                    updateOrderString.Append("IF EXISTS (select * from YW_OrderDetail where OrderChildId='" + g_oid + "') update YW_OrderDetail set OrderId='" + g_tid + "',OrderChildId='" + g_oid + "',VarietyId='" + g_cat_id + "',VarietyName='" + g_cat_name + "',GoodsId='" + g_sku_id + "',GoodsName='" + g_title + "',BuyChickCount='" + g_num + "',SendNum='" + g_sendnum + "',LossCount='" + g_loss_number + "',AdjustNumber='" + g_adjust_number + "',WaitDeliveryTime=" + TimeStamp.unixTimeToTime(g_wait_delivery_time.ToString()) + ",ValueAdded_Content='" + ValueAdded_content + "' where OrderChildId='" + g_oid + "'");
                                    updateOrderString.Append("  ELSE insert into YW_OrderDetail (OrderId,OrderChildId,VarietyId,VarietyName,GoodsId,GoodsName,BuyChickCount,SendNum,LossCount,AdjustNumber,WaitDeliveryTime,ValueAdded_Content) values('" + g_tid + "','" + g_oid + "','" + g_cat_id + "','" + g_cat_name + "','" + g_sku_id + "','" + g_title + "','" + g_num + "','" + g_sendnum + "','" + g_loss_number + "','" + g_adjust_number + "'," + TimeStamp.unixTimeToTime(g_wait_delivery_time.ToString()) + ",'" + ValueAdded_content + "' );");
                                    #endregion
                                }
                                #endregion 【拼接同步商品信息sql结束】
                            }
                        }

                        #endregion【拼接同步订单、商品信息sql结束】
                        //执行sql
                        _helper.ExecuteNonQuery(orderBaseString.ToString());
                        _helper.ExecuteNonQuery(updateOrderString.ToString());
                        //同步成功，加入日志 对取消订单的信息进行处理，删除分厅信息和排线信息，备份到备份表中去
                        string sql = "";
                        if (type == 1)
                        {

                            //sql = "Insert into YW_GivetohallInfo_bak select *,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason from YW_GivetohallInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );delete from YW_GivetohallInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );";//备份分厅表SQL
                            //sql += "Insert into YW_TaskOrderRelation_bak select *,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason from YW_TaskOrderRelation where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );delete from YW_TaskOrderRelation where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );";//备份任务订单关系表
                            //sql += "Insert into YW_TaskCarRelation_bak select *,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason from YW_TaskCarRelation where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  ); delete from YW_TaskCarRelation where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );";//备份任务车辆订单关系表
                            sql = "Insert into YW_GivetohallInfo_bak select Id, OrderId, OrderChildId, BaseId, BaseName, HallId, HallName, VarietyId, VarietyName, GoodsId, GoodsName, BuyChickCount, HallLossCount, CreateUserId, CreateTime, ModifyTime,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason,Remarks from YW_GivetohallInfo where OrderId in (select OrderCode from YW_OrderInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );delete from YW_GivetohallInfo where OrderId in (select OrderCode from YW_OrderInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );";//备份分厅表SQL
                            sql += "Insert into YW_TaskOrderRelation_bak select Id, TaskId, OrderId, GivetohallId, BaseId, BaseName, HallId, HallName, VarietyId, VarietyName, GoodsId, GoodsName, CarNumber, Sort, OrderDeliveryStatus, IsMore, IsChange, SignPath, SignTime,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason  from YW_TaskOrderRelation where OrderId in (select OrderCode from YW_OrderInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );delete from YW_TaskOrderRelation where OrderId in (select OrderCode from YW_OrderInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );";//备份任务订单关系表
                            sql += "Insert into YW_TaskCarRelation_bak select Id, TaskId, OrderId, TaskOrderId, BaseId, BaseName, HallId, HallName, CarNumber, SensorId, GPSId, MainDriverId, MainDriverName, MainDriverTel, AssistantDriverId, AssistantDriverName, AssistantDriverTel, OrderChickCountInCar, HallLossCount, CarLossCount, CarDeliveryStatus, FinishType, SignPath, SignTime,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason, CarDeliveryTaskStatus, CarLeaveTime, CarArriveTime  from YW_TaskCarRelation where OrderId in (select OrderCode from YW_OrderInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  ); delete from YW_TaskCarRelation where OrderId in (select OrderCode from YW_OrderInfo where OrderId in ('" + String.Join("','", orderids.Split(',')) + "')  and CancelStatus='SUCCESS'  );";//备份任务车辆订单关系表
                        }
                        else if (type == 2)
                        {
                            sql = "Insert into YW_GivetohallInfo_bak select Id, OrderId, OrderChildId, BaseId, BaseName, HallId, HallName, VarietyId, VarietyName, GoodsId, GoodsName, BuyChickCount, HallLossCount, CreateUserId, CreateTime, ModifyTime,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason,Remarks from YW_GivetohallInfo where OrderId in (select OrderCode from YW_OrderInfo where WaitDeliveryTime between '" + start.ToString("yyyy-MM-dd") + " 00:00:00' and  '" + end.ToString("yyyy-MM-dd") + " 23:59:59' and CancelStatus='SUCCESS'  );delete from YW_GivetohallInfo where OrderId in (select OrderCode from YW_OrderInfo where WaitDeliveryTime between '" + start.ToString("yyyy-MM-dd") + " 00:00:00' and  '" + end.ToString("yyyy-MM-dd") + " 23:59:59' and CancelStatus='SUCCESS'  );";//备份分厅表SQL
                            sql += "Insert into YW_TaskOrderRelation_bak select Id, TaskId, OrderId, GivetohallId, BaseId, BaseName, HallId, HallName, VarietyId, VarietyName, GoodsId, GoodsName, CarNumber, Sort, OrderDeliveryStatus, IsMore, IsChange, SignPath, SignTime,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason from YW_TaskOrderRelation where OrderId in (select OrderCode from YW_OrderInfo where WaitDeliveryTime between '" + start.ToString("yyyy-MM-dd") + " 00:00:00' and  '" + end.ToString("yyyy-MM-dd") + " 23:59:59' and CancelStatus='SUCCESS'  );delete from YW_TaskOrderRelation where OrderId in (select OrderCode from YW_OrderInfo where WaitDeliveryTime between '" + start.ToString("yyyy-MM-dd") + " 00:00:00' and  '" + end.ToString("yyyy-MM-dd") + " 23:59:59' and CancelStatus='SUCCESS'  );";//备份任务订单关系表
                            sql += "Insert into YW_TaskCarRelation_bak select Id, TaskId, OrderId, TaskOrderId, BaseId, BaseName, HallId, HallName, CarNumber, SensorId, GPSId, MainDriverId, MainDriverName, MainDriverTel, AssistantDriverId, AssistantDriverName, AssistantDriverTel, OrderChickCountInCar, HallLossCount, CarLossCount, CarDeliveryStatus, FinishType, SignPath, SignTime,(select CancelReason from YW_OrderInfo where OrderCode=OrderId)CancelReason, CarDeliveryTaskStatus, CarLeaveTime, CarArriveTime from YW_TaskCarRelation where OrderId in (select OrderCode from YW_OrderInfo where WaitDeliveryTime between '" + start.ToString("yyyy-MM-dd") + " 00:00:00' and  '" + end.ToString("yyyy-MM-dd") + " 23:59:59' and CancelStatus='SUCCESS'  ); delete from YW_TaskCarRelation where OrderId in (select OrderCode from YW_OrderInfo where WaitDeliveryTime between '" + start.ToString("yyyy-MM-dd") + " 00:00:00' and  '" + end.ToString("yyyy-MM-dd") + " 23:59:59' and CancelStatus='SUCCESS'  );";//备份任务车辆订单关系表
                        }
                        _helper.ExecuteNonQuery(sql.ToString());
                        //return "同步成功！";
                    }
                    else
                    {
                        //获取数据列表为空
                        return "未获取数据";
                    }
                }
                else
                {
                    //数据获取有误，写入日志
                    //-------从接口获取数据失败，写入日志
                    return "解析数据有误请联系管理员！";
                }
            }
            while (totalPage >= currentPage);
            return "同步成功！";
        }
	}
}
